﻿using Autodesk.Windows;
using LeonCad.Core.Ribbons.Extension;
using Newtonsoft.Json;
using SkiaSharp;
using Svg.Skia;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices.ComTypes;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace AcadRibbon.Ribbons.Json;

/// <summary>
/// 图片转换
/// </summary>
internal class ImageSourceConverter : JsonConverter<System.Windows.Media.ImageSource> {
    private bool LargeImage;

    public override ImageSource? ReadJson(JsonReader reader, Type objectType, ImageSource? existingValue, bool hasExistingValue, JsonSerializer serializer) {
        if (reader.Path == RibbonItem.LargeImagePropertyName
            || reader.Path == RibbonItem.ImagePropertyName
            || reader.Path == "ToolTip.ExpandedImage") {
            string? imgPath = reader.Value?.ToString();
            if (imgPath != null && !string.IsNullOrEmpty(imgPath)) {
                LargeImage = reader.Path == RibbonItem.LargeImagePropertyName;
                var bitmap = GetImageForm(Assembly.GetExecutingAssembly(), imgPath)
                    ?? GetImageForm(imgPath);

                return bitmap;// LoadImage(imgPath);
            }
        }
        return null;
    }

    public override void WriteJson(JsonWriter writer, ImageSource? value, JsonSerializer serializer) {
        throw new NotImplementedException();
    }

    internal BitmapImage? GetImageForm(Assembly asm, string resourceName) {
        var resourcefileName = asm.GetManifestResourceNames()
              .Where(s => s.Contains(resourceName.Replace(@"\", ".")))
              .FirstOrDefault();
        if (!string.IsNullOrWhiteSpace(resourcefileName)) {
            var stream = asm.GetManifestResourceStream(resourcefileName);
            if (stream == null)
                return null;

            if (resourcefileName.EndsWith(".svg")) {
                return stream.ConvertSvgToBitmapImage(LargeImage ? new(24, 24) : new(14, 14));
            } else {
                return RibbonConverExtension.BitmapToBitmapImage(new(stream));
            }
        }
        return null;
    }

    internal BitmapImage? GetImageForm(string resourceName) {
        var dirPath = Directory.GetCurrentDirectory();
        var fielName = Path.Combine(dirPath, resourceName);
        if (dirPath.DirExists(resourceName.Substring(resourceName.LastIndexOf(@"\") + 1), out var path))
            fielName = path;

        if (File.Exists(fielName)) {
            if (Path.GetExtension(fielName) == ".svg") {
                using var stream = File.OpenRead(fielName);
                return stream.ConvertSvgToBitmapImage(LargeImage ? new(24, 24) : new(14, 14));
            } else {
                return new(new Uri(path));
            }
        }

        return null;
    }
}